var express = require('express');
var router = express.Router();
// 加密算法
const crypto = require('crypto')

// 直接对cookie 值加密

// 加密原理解析

router.get('/secret', (req, res) => {
  let password = "123456";
  let sf = crypto.createHash("md5")
  // 二进制数据
  sf.update(password)
  // 转为十六进制
  let content = sf.digest('hex')
  res.send(content)
})



/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/setCookie', (req, res) => {
  // 设置cookie,有效期默认为一个会话
  // res.cookie("isLogin", "true")
  // cookie 设置时间
  // res.cookie('isLogin',"true",{maxAge:10000,httpOnly:true})
  // 设置加密操作
  res.cookie('isLogin', 'true', { signed: true })
  res.send('cookie set success')
})

// cookie 解码

router.get('/admin', (req, res) => {
  if (req.cookies.isLogin == 'true') {
    res.send('登录成功')
  } else {
    res.send('登录失败')
  }
})

router.get('/adminCookie', (req, res) => {
  console.log(req.signedCookies)
  if (req.signedCookies.isLogin == 'true') {
    res.send('success')
  } else {
    res.send('warn')
  }
})


let CookiesList = {};
let encryption = (str) => {
  let password = str;
  let sf = crypto.createHash("md5")
  // 二进制数据
  sf.update(password)
  // 转为十六进制
  return sf.digest('hex')
}

let getCookies = (password) => {
  return CookiesList.password
}
let setCookies = (str, password) => {
  CookiesList.password = str;
}

router.get('/myCookie', (req, res) => {
  let str = '123456';
  let password = encryption(str);
  setCookies(str, password)
  res.cookie('psw', password)
  res.send('aaa')
})

router.get('/getCookies', (req, res) => {
  res.send(getCookies(getCookies(req.query.cookieValue)))
})



module.exports = router;
